class AccountController < ApplicationController
  def login
    if request.get?
      logout_user
    else
      authenticate_user
    end
  end

  def logout
    logout_user
    redirect_to home_url
  end

  def register
    if request.get?
      @user = User.new
      @user.build_profile
    else
      @user = User.new(params[:user])
      @user.build_settings(:country => Setting.default_country, :language => Setting.default_language, :timezone => Setting.default_timezone)

      respond_to do |format|
        if @user.save
          format.html { redirect_to signin_path, notice: 'User was successfully created.' }
          format.json { render json: @user, status: :created, location: @user }
        else
          format.html { render action: :register }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  private

  def authenticate_user
    password_authentication
  end

  def password_authentication
    user = User.try_to_login(params[:username], params[:password])

    if user.nil?
      invalid_credentials
    elsif user.new_record?
      onthefly_creation_failed(user)
    else
      successful_authentication(user)
    end
  end

  def invalid_credentials
    logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
    flash.now[:error] = "Failed login"

    respond_to do |format|
      format.html { redirect_to signin_path }
      format.json { render json: nil }
    end
  end

  def onthefly_creation_failed(user)
    @user = user
    render :action => 'register'
  end

  def successful_authentication(user)
    logger.info "Successful authentication for '#{user.username}' from #{request.remote_ip} at #{Time.now.utc}"

    self.logged_user = user

    respond_to do |format|
      format.html { redirect_to my_page_path }
      format.json { render json: user }
    end
  end
end